﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Atm.BLL;

public partial class usercontrol_ucHeader : HocLapTrinhWeb.UI.UCBase
{
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        CheckLogin();
        divUser.InnerHtml = "<a href='#'>" + (Session["FullName"] == null ? "Guest" : Session["FullName"].ToString()) + "</a><span>|</span><a href='" + CurrentPage.UrlRoot + "/admin/login.aspx?logout=1'>Thoát</a>";
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session.Remove("UserName");
        Session.Remove("UserID");
        Session.Remove("FullName");
        Session.Remove("IsAdmin");
        Response.Cookies["UserName"].Expires = DateTime.Now;
        Response.Redirect("~/admin/Login.aspx");
    }



    /// <summary>
    /// Show Hide Dashboard Admin
    /// </summary>
    private void CheckLogin()
    {
        if (Session["UserName"] == null)
        {
            if (Request.Cookies["UserName"] != null)
            {
                if (!Login())
                    divUser.Visible = false;
                else
                    divLogin.Visible = false;
                return;
            }
            divUser.Visible = false;
        }
        else
        {
            //if (Session["IsAdmin"] == null || (bool)Session["IsAdmin"] == false)
            //    divLogin.Visible = false;
            divLogin.Visible = false;
        }
    }

    /// <summary>
    /// Check login bang cookie
    /// </summary>
    /// <returns></returns>
    private bool Login()
    {
        try
        {
            var userBll = new v_UserBLL(CurrentPage.getCurrentConnection());
            var row = userBll.GetUserByName(Request.Cookies["UserName"].Values["UserName"]);
            if (row == null)
            {
                return false;
            }
            if (!row.IsActive)
            {
                return false;
            }
            if (row.Pass != Request.Cookies["UserName"].Values["Password"])
            {
                return false;
            }
            Session["UserName"] = row.UserName;
            Session["FullName"] = row.FullName;
            Session["UserID"] = row.UserID.ToString();
            Session["IsAdmin"] = row.IsAdmin;
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }


}